﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCCommon
{
    /// <summary>
    /// 坐标操作
    /// </summary>
    public static class CoordinateUtils
    {
        private const double EARTH_RADIUS = 6378137;
        /// <summary>
        /// 计算两点位置的距离，返回两点的距离，单位 米
        /// 该公式为GOOGLE提供，误差小于0.2米
        /// </summary>
        /// <param name="fromLng">第一点经度</param>
        /// <param name="fromLat">第一点纬度</param>
        /// <param name="toLng">第二点经度</param>
        /// <param name="toLat">第二点纬度</param>
        /// <returns></returns>
        public static double CoordinateDifference(double fromLng, double fromLat, double toLng, double toLat)
        {
            double radFromLng = Rad(fromLng);
            double radFromLat = Rad(fromLat);
            double radToLng = Rad(toLng);
            double radToLat = Rad(toLat);
            double a = radFromLng - radToLng;
            double b = radFromLat - radToLat;
            double result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(b / 2), 2) + Math.Cos(radFromLat) * Math.Cos(radToLat) * Math.Pow(Math.Sin(a / 2), 2))) * EARTH_RADIUS;
            return result;
        }
        /// <summary>
        /// 经纬度转化成弧度
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private static double Rad(double d)
        {
            return (double)d * Math.PI / 180d;
        }
    }
}
